# -*- coding: utf-8 -*-
#
# Tubemaster
#
# Copyright (C) 2009 Selim Ok <selimok@gmail.com>
# Copyright (C) 2007-2008 Siegfried-Angel Gevatter Pujals <siggi.gevatter@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

import threading, subprocess
import shutil
import os
from os import devnull

class Converter(threading.Thread):

    def __init__(self, destdir, filename, param ="-ar 44100 -ac 2 -aab 128 -sameq"):
        self.destdir = destdir
        self.filename = filename
        self.path = os.path.join(self.destdir,self.filename)
        self.partial_filename = self.filename + '.part'
        self.partial_path = os.path.join(self.destdir,self.partial_filename)
        self.param = param
        self.error = None
        self.stderror = None
        threading.Thread.__init__(self)

    def setError(self,text):
        self.error = text

    def run(self):
        try:
            # Call ffmpeg for converting downloaded video
            self.pipe = subprocess.Popen(
                            'ffmpeg ' + '-y -i \"' + str(self.partial_path) + '\" ' + str(self.param) + ' \"' + str(self.path) + '\"',
                                shell=True, 
                                stdin=None,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                            )
            # Read the resulting output
            self.stderror = self.pipe.stderr.readlines()
            self.stdout = self.pipe.stdout.readlines()
            print "out :"
            print self.stdout
            print "error :"
            print self.stderror

            #An error occured
            if((str(self.stderror).lower()).find('Error while opening codec for output stream')>=0):
                self.setError("Error while opening codec for output stream!")
                if os.path.exists(self.path):
                    os.remove(self.path)
            else:
                self.setError(0)

            os.remove(self.partial_path)

        except IOError:
            pass	# The process was killed, probably because the user closed the GUI
